package com.example.dbsample.util.dynamicconnection;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.NamedThreadLocal;

import java.util.ArrayDeque;
import java.util.Deque;

public final class DynamicDataSourceContextHolder {
    private static final ThreadLocal<Deque<String>> LOOKUP_KEY_HOLDER = new NamedThreadLocal<Deque<String>>("dynamic-datasource") {
        protected Deque<String> initialValue() {
            return new ArrayDeque();
        }
    };

    private DynamicDataSourceContextHolder() {

    }

    public static String peek() {
        return (String)((Deque) LOOKUP_KEY_HOLDER.get()).peek();
    }

    public static String push(String ds) {
        String dataSourceStr = StringUtils.isEmpty(ds) ? "" : ds;
        ((Deque)LOOKUP_KEY_HOLDER.get()).push(dataSourceStr);
        return dataSourceStr;
    }

    public static void poll() {
        Deque<String> deque = (Deque) LOOKUP_KEY_HOLDER.get();
        deque.poll();
        if(deque.isEmpty()) {
            LOOKUP_KEY_HOLDER.remove();
        }
    }

    public static void clear() {
        LOOKUP_KEY_HOLDER.remove();
    }
}
